<template>
    <div class="form-main">
        <el-form ref="formRef" :model="formParams" :rules="rules" label-width="126px" :disabled="disabled">
            <div class="base-info">
                <div class="form-title">基础信息设置</div>
                <el-form-item label="活动名称" prop="activity_name">
                    <el-input
                        v-model.trim="formParams.activity_name"
                        maxlength="20"
                        show-word-limit
                        placeholder="请输入活动名称" />
                </el-form-item>
                <el-form-item
                    label="活动有效期"
                    prop="period_type"
                    class="form-radio-item"
                    :class="{ 'activity-time': formParams.period_type === 2 }">
                    <el-radio-group
                        v-model="formParams.period_type"
                        prop="period_type"
                        @change="handlePeriodTypeChange">
                        <el-radio :label="1">永久</el-radio>
                        <el-radio :label="2">自定义期限</el-radio>
                    </el-radio-group>
                    <el-form-item v-if="formParams.period_type === 2" class="activity-time-two">
                        <div v-if="formDisabled" class="edit-activity-time">
                            <el-date-picker
                                v-model="formParams.activity_time[0]"
                                disabled
                                type="datetime"
                                format="YYYY-MM-DD HH:mm:ss"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                placeholder="开始时间" />
                            <el-date-picker
                                v-model="formParams.activity_time[1]"
                                prefix-icon="none"
                                type="datetime"
                                format="YYYY-MM-DD HH:mm:ss"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                placeholder="结束时间"
                                :disabled-date="disabledDate"
                                :default-time="new Date(2000, 1, 1, 23, 59, 59)"
                                @change="checkActivityTime" />
                        </div>
                        <el-date-picker
                            v-else
                            v-model="formParams.activity_time"
                            type="datetimerange"
                            :disabled-date="disabledDate"
                            :default-time="defaultTime()"
                            format="YYYY-MM-DD HH:mm:ss"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            range-separator="⇀"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            @change="checkActivityTime" />
                    </el-form-item>
                </el-form-item>
                <el-form-item label="活动说明" prop="description">
                    <el-input
                        v-model="formParams.description"
                        style="width: 420px"
                        type="textarea"
                        maxlength="500"
                        :rows="5"
                        show-word-limit
                        placeholder="请输入活动说明" />
                </el-form-item>
            </div>
            <div id="clockInContent" class="rules-info">
                <div class="form-title form-title-top">打卡规则设置</div>
                <el-form-item label="打卡口令" prop="clock_password">
                    <el-input
                        v-model.trim="formParams.clock_password"
                        maxlength="20"
                        show-word-limit
                        placeholder="请输入打卡口令" />
                </el-form-item>
                <el-form-item label="打卡奖励" prop="points_num">
                    <div class="points-num">
                        <span>每日打卡可获得</span>
                        <el-input v-model.trim="formParams.points_num" class="points-num-input" placeholder="请输入" />
                        <span>积分</span>
                    </div>
                </el-form-item>
                <el-form-item label="打卡时间段" prop="clock_time_range">
                    <div v-for="(item, index) in formParams.clock_time_range" :key="index" class="clock-time-item">
                        <el-time-picker
                            :id="index"
                            :key="`time_${index}`"
                            v-model="formParams.clock_time_range[index]"
                            style="width: 400px"
                            is-range
                            :default-value="defaultTime()"
                            format="HH:mm"
                            value-format="HH:mm"
                            range-separator="⇀"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间" />
                        <el-icon
                            v-show="formParams.clock_time_range?.length > 1 && !disabled"
                            @click="onTimeDel(index)">
                            <CircleCloseFilled />
                        </el-icon>
                    </div>
                    <div class="clock-time-btn">
                        <el-button
                            type="primary"
                            plain
                            :disabled="formParams.clock_time_range?.length >= 5"
                            @click="onAddTime">
                            <el-icon><Plus /></el-icon>
                            <span>添加时间段</span>
                        </el-button>
                    </div>
                </el-form-item>
                <el-form-item
                    label="打卡可用群聊"
                    prop="clock_groupchat"
                    class="clock-group-chat"
                    :class="{ 'clock-group-chat-active': formParams.clock_groupchat == 1 }">
                    <el-radio-group
                        v-model="formParams.clock_groupchat"
                        prop="clock_groupchat"
                        @change="onGroupChatChange">
                        <el-radio :label="1">全部群聊</el-radio>
                        <el-radio :label="2">指定群聊</el-radio>
                    </el-radio-group>
                    <template v-if="formParams.clock_groupchat == 2">
                        <div class="group-chat-btn">
                            <el-button type="primary" plain @click="onGroupChat">
                                <el-icon><Plus /></el-icon>
                                <span>添加群聊</span>
                            </el-button>
                            <div v-show="formParams.groupchat_list.length" class="group-chat-btn-desc">
                                已选群聊 <span>{{ formParams.groupchat_list.length }}</span> 个
                            </div>
                        </div>
                        <div class="group-chat-list">
                            <div
                                v-for="(item, index) in formParams.groupchat_list"
                                v-show="index < 4"
                                :key="index"
                                class="list-item">
                                <el-image class="item-img" :src="item?.avatar" />
                                <div class="item-name">{{ item?.name }}</div>
                                <el-icon v-if="!disabled" @click="onGroupChatDel(index)"><CircleCloseFilled /></el-icon>
                            </div>
                            <div
                                v-show="formParams.groupchat_list.length > 4"
                                class="list-btn"
                                :class="{ 'list-btn-disabled': disabled }"
                                @click="onGroupChat">
                                …
                            </div>
                        </div>
                    </template>
                </el-form-item>
                <el-form-item prop="groupchat_list" class="group-chat-text-wrap">
                    <div class="group-chat-text">
                        <div>
                            1）群打卡活动只能个人微信用户参与，同一活动若多次打卡或在多个群内参与，只会记录最早参与的一次；
                        </div>
                        <div>2）在打卡时间段内打卡才算有效打卡，用户打卡成功后退群，奖励仍然会保留；</div>
                        <div>
                            3）群打卡仅限于开启会话存档的群才能使用，即群内必须要有开启会话存档的员工，若该员工退群或离职后将无法获取打卡数据；
                        </div>
                        <div>
                            4）若同一个群有多个活动存在，且打卡口令一样，则多个活动都会打卡成功，请注意最好不要配置重复活动。
                        </div>
                    </div>
                </el-form-item>
            </div>
            <div class="script-info">
                <div class="form-title form-title-top">话术设置</div>
                <el-form-item label="打卡话术" prop="welcome_info">
                    <material-content
                        id="welcomeMaterialContent"
                        ref="scriptWelcomeRef"
                        re-key="scriptWelcome"
                        :disabled="disabled"
                        :input-content-tabs="inputContentTabs"
                        :show-material-tabs="showMaterialTabs"
                        :input-content-data="formParams.welcome_info.welcome_text"
                        :material-content-data="defaultMaterialContentData"
                        :placeholder="'请输入欢迎语'"
                        @change="changeMaterial" />
                </el-form-item>
            </div>
        </el-form>
    </div>
    <group-chart ref="groupChartRef" :type="queryType" :is-disabled-name="false" @submit="onSubmitGroup" />
</template>
<script setup lang="ts">
import groupChart from '@/components/zw/groupChart/index.vue';
import materialContent from '@/components/zw/materialContent1.0/index.vue';
import { ref, reactive, computed } from 'vue';
import { useRoute } from 'vue-router';
import { FormInstance } from 'element-plus';
import { defaultTime, initMaterialData } from '@/utils/utils';
import { cloneDeep } from 'lodash';
import dayjs from 'dayjs';
import isBetween from 'dayjs/plugin/isBetween';

// 校验两者之间的插件
dayjs.extend(isBetween);

const route = useRoute();

const emit = defineEmits(['update:modelValue']);

const props = defineProps({
    modelValue: {
        type: Object,
        default: () => {}
    },
    isShortLink: {
        type: [Boolean, String],
        default: false
    }
});

const formParams = computed({
    get() {
        return props.modelValue;
    },
    set(val) {
        emit('update:modelValue', val);
    }
});

const disabled = computed(() => {
    return route.query.type == 'look';
});

const queryType = ref<any>(route.query.type);

const formRef = ref<FormInstance>();

/**
 * @description 选择群聊弹窗实例
 */
const groupChartRef = ref<any>();

const formDisabled = computed(() => {
    return formParams.value.activity_status !== 1 && route.query.type == 'edit';
});

const disabledDate = (data: any) => {
    // 编辑状态下禁用活动创建之前
    if (formDisabled?.value && formParams.value.created_at) {
        return +data < +new Date(formParams.value.created_at) - 86400000;
    }
    // 86400000 => 一天的时间毫秒
    return +data < +new Date() - 86400000;
};

// 话术内容ref实例化
const scriptWelcomeRef = ref();
/**
 * @description 欢迎语输入框选项
 * 1: 选择文本，2:表情，8: 打卡口令，9:打卡查询短链
 */
const inputContentTabs = computed(() => {
    const list = [1, 2, 8];
    if (props.isShortLink) {
        list.push(9);
    }
    return list;
});

/**
 * @description 欢迎语素材类型
 * 1: 图片, 2: 视频, 3: 链接, 4: 音频, 5: 文件, 6: 抽奖， 7: 电商， 8: 电商, 9: 收集表,10 公众号, 11: 小程序
 */
const showMaterialTabs = ref<Array<string>>(['1', '2', '3', '4', '5', '7', '9', '10', '11']);

/**
 * 默认内容
 */
const defaultMaterialContentData = ref<Array<any>>([]);
// is_default_del这个字段，是否默认能删除 1：否 2: 是
const defaultData = [
    {
        type: 11,
        title: '快来查看你的打卡结果吧！',
        link_decs: '打开查看您的社群打卡记录和打卡奖励',
        icon: 'https://static.scrm.keyid.cn/assets/images/web-pc/default-mini-app.jpg',
        absolute_url: 'https://static.scrm.keyid.cn/assets/images/web-pc/default-mini-app.jpg',
        is_default_del: 1
    }
];
// 入群欢迎语
defaultMaterialContentData.value = initMaterialData(defaultData);

/**
 * 校验活动名称
 * @param ruls
 * @param value
 * @param callback
 */
const checkActivityName = (ruls: any, value: any, callback: any) => {
    if (!value) {
        return callback(new Error('请输入活动名称'));
    }

    if (value.length > 20) {
        return callback(new Error('请输入20个文字以内的活动名称'));
    }

    callback();
};

/**
 * 校验活动时间
 * @param ruls
 * @param value
 * @param callback
 */
const checkPeriodType = (ruls: any, value: any, callback: any) => {
    if (!value) {
        return callback(new Error('请选择活动有效期类型'));
    }

    if (value === 2) {
        const result = formParams.value.activity_time?.every((item: any) => item);
        if (!result || formParams.value.activity_time?.length < 2) return callback(new Error('请选择活动有效期'));

        // 校验结束时间和开始时间
        const [startTime, endTime] = formParams.value.activity_time;
        if (+new Date(startTime) >= +new Date(endTime)) {
            return callback(new Error('活动结束时间不能小于活动开始时间'));
        }
    }
    callback();
};

/**
 * 校验打卡口令
 * @param ruls
 * @param value
 * @param callback
 */
const checkClockPassword = (ruls: any, value: any, callback: any) => {
    if (!value) {
        return callback(new Error('请输入打卡口令'));
    }

    if (value.length > 20) {
        return callback(new Error('请输入20个文字以内的打卡口令'));
    }

    callback();
};

/**
 * 校验打卡奖励
 * @param ruls
 * @param value
 * @param callback
 */
const checkPointsNum = (ruls: any, value: any, callback: any) => {
    if (!value) {
        return callback(new Error('请输入打卡奖励'));
    }
    const reg = /^[1-9]\d*$|^0$/;
    if (!reg.test(value) || value > 1000000 || value <= 0) {
        return callback(new Error('请输入1~100万之间的整数'));
    }

    callback();
};

/**
 * 校验群聊
 * @param rule
 * @param value
 * @param callback
 */
const checkClockGroupchat = (rule: any, value: any, callback: any) => {
    if (value == 1) {
        return callback();
    }
    if (!formParams.value.groupchat_list.length) {
        return callback(new Error('请添加群聊'));
    }
    callback();
};

/**
 * 校验话术内容
 * @param rule
 * @param value
 * @param callback
 */
const checkWelcomeInfo = (rule: any, value: any, callback: any) => {
    if (!formParams.value.welcome_info.welcome_text) {
        return callback(new Error('请设置添加话术内容'));
    }

    callback();
};

/**
 * 校验固定时间段
 */
const checkEnableTime = (rule: any, value: any, callback: any) => {
    if (!value || !value.length) {
        return callback(new Error('请选择打卡时间段'));
    }
    if (value.some((el: any) => !el?.length)) {
        return callback(new Error('请选择打卡时间段'));
    }
    // 双循环判断时间是否重复
    const nowTime = dayjs().format('YYYY/MM/DD');
    formParams.value.clock_time_range.map((timeItem: any, index: number) => {
        let [beginTime, endTime] = timeItem;
        if (!beginTime || !endTime) {
            return callback(new Error('请选择启用时段'));
        }
        beginTime = `${nowTime} ${beginTime}`;
        endTime = `${nowTime} ${endTime}`;
        // 校验的时间
        formParams.value.clock_time_range.map((checkTimeItem: any, idx: number) => {
            if (
                (checkTimeItem[0] == timeItem[0] && checkTimeItem[1] == timeItem[1] && index != idx) ||
                (checkTimeItem[1] == timeItem[0] && index != idx)
            ) {
                return callback(new Error('时间段不能交叉'));
            }
            let [checkBeginTime, checkEndTime] = checkTimeItem;
            checkBeginTime = `${nowTime} ${checkBeginTime}`;
            checkEndTime = `${nowTime} ${checkEndTime}`;
            const beginCheckResult = dayjs(beginTime).isBetween(checkBeginTime, checkEndTime);
            const endCheckResult = dayjs(endTime).isBetween(checkBeginTime, checkEndTime);
            // 如果有任一一个是重复了，则校验失败
            if (beginCheckResult || endCheckResult) {
                return callback(new Error('时间段不能交叉'));
            }
        });
    });
    callback();
};

/**
 * 表单校验规则
 */
const rules = reactive({
    activity_name: [{ required: true, validator: checkActivityName, trigger: 'change' }],
    period_type: [{ required: true, validator: checkPeriodType, trigger: 'blur' }],
    clock_password: [{ required: true, validator: checkClockPassword, trigger: 'blur' }],
    points_num: [{ required: true, validator: checkPointsNum, trigger: 'blur' }],
    clock_time_range: [{ required: true, validator: checkEnableTime, trigger: 'change' }],
    clock_groupchat: [{ required: true, validator: checkClockGroupchat }],
    welcome_info: [{ required: true, validator: checkWelcomeInfo }]
});

/**
 * 活动结束时间变更时校验开始和结束时间
 */
const checkActivityTime = () => {
    formRef.value?.validateField(['period_type']);
};

/**
 * 添加员工推送欢迎语更改内容时回调，实时变更v-model的值
 */
const changeMaterial = (val: any) => {
    val.welcome_info.welcome_friend_id =
        val.welcome_info.welcome_friend_id || formParams.value.welcome_info.welcome_friend_id;
    formParams.value.welcome_info = val.welcome_info;
};

/**
 * 活动有效期类型
 */
const handlePeriodTypeChange = () => {
    formRef.value?.clearValidate(['period_type']);
    // 非编辑页面，不做设置默认值
    if (route.query.type != 'edit') {
        return;
    }
    if (formParams.value.period_type === 2 && !formParams.value.activity_time.length) {
        formParams.value.activity_time = [formParams.value.created_at, null];
    }
};

/**
 * 切换群聊
 */
const onGroupChatChange = () => {};

/**
 * 打开群聊弹框，需要数据回显
 * @param evt
 */
const onGroupChat = (evt: any) => {
    if (disabled.value) return;
    const target = evt.target;
    if (target.nodeName == 'BUTTON' || target.nodeName == 'SPAN') {
        target.parentNode.blur();
    }
    target.blur();
    groupChartRef.value.appDialog.visible = true; // 展示群聊弹窗
    groupChartRef.value.selectList = cloneDeep(formParams.value.groupchat_list);
};

/**
 * 确认群聊弹框
 */
const onSubmitGroup = (list: any = []) => {
    formParams.value.groupchat_list = list;
    formRef.value?.validateField(['clock_groupchat']);
};

/**
 * 删除群聊
 */
const onGroupChatDel = (index: number) => {
    formParams.value.groupchat_list.splice(index, 1);
};

/**
 * 添加时间段
 */
const onAddTime = (evt: any) => {
    const target = evt.target;
    if (target.nodeName == 'BUTTON' || target.nodeName == 'SPAN') {
        target.parentNode.blur();
    }
    target.blur();
    if (formParams.value.clock_time_range?.length >= 5) return;
    formParams.value.clock_time_range.push([]);
};

/**
 * 时间端删除
 */
const onTimeDel = (index: number) => {
    formParams.value.clock_time_range.splice(index, 1);
    formRef.value?.validateField(['clock_time_range']);
};

/**
 * 表单校验validate
 */
const validate = async () => {
    return await formRef.value?.validate();
};

/**
 * 设置话术内容-详情回显
 */
const setWelcomeInfo = (data: any) => {
    data.welcome_material.map((el: any) => {
        if (el.is_default_del == 1 && el.type == 3) {
            el.type = 11;
            el.title = '快来查看你的打卡结果吧！';
            el.icon = el.link_share_image;
            el.absolute_url = el.link_share_image;
        }
    });
    defaultMaterialContentData.value = initMaterialData(data.welcome_material);
};

defineExpose({
    setWelcomeInfo,
    validate
});
</script>
<style lang="scss" scoped>
.form-main {
    margin: 22px 26px;

    .el-form-item {
        margin-bottom: 24px;
    }

    .activity-time-two {
        margin-top: 16px;
        margin-bottom: 0;
    }

    .el-input {
        width: 420px;
        max-width: 420px;
    }

    .clock-group-chat {
        margin-bottom: 16px;
    }

    .clock-group-chat-active {
        margin-bottom: 8px;
    }

    :deep(.el-form-item__error) {
        padding-top: 4px;
    }
}

.form-title {
    display: flex;
    align-items: center;
    margin-bottom: 24px;
    color: #333;
    font-size: 16px;
    font-family: PingFangSC-Medium, 'PingFang SC';
    font-weight: 500;

    &::before {
        width: 3px;
        height: 16px;
        margin-right: 6px;
        content: '';
        border-radius: 2px;
        background-color: #ff6b00;
    }
}

.form-title-top {
    margin-top: 36px;
}

:deep(.edit-activity-time) {
    display: flex;
    width: 420px;

    .el-input__wrapper {
        border: 1px solid var(--el-input-border-color);
        border-radius: 0;
        box-shadow: none;
    }

    .el-date-editor:first-child {
        .el-input__wrapper {
            border-right: 0;
            border-radius: var(--el-input-border-radius) 0 0 var(--el-input-border-radius);
        }

        &::after {
            position: absolute;
            z-index: 2;
            right: 0;
            content: '-';
            transform: translateX(50%);
            color: #ccc;
        }
    }

    .el-date-editor:last-child {
        .el-input__wrapper {
            border-left: 0;
            border-radius: 0 var(--el-input-border-radius) var(--el-input-border-radius) 0;
        }
    }

    .el-input__prefix {
        margin-right: 6px;
    }
}

.points-num {
    display: flex;
    align-items: center;

    .points-num-input {
        margin: 0 8px;
        width: 90px;
    }

    span {
        font-size: 14px;
        color: #333;
        line-height: 20px;
    }
}

.clock-time-item {
    margin-bottom: 16px;
    white-space: nowrap;

    .el-icon {
        margin-left: 24px;
        font-size: 16px;
        color: #ccc;

        &:hover {
            cursor: pointer;
            color: var(--el-text-color-placeholder);
        }
    }
}

.group-chat-btn {
    margin-top: 8px;
    display: flex;
    align-items: center;

    .group-chat-btn-desc {
        margin-left: 16px;
        font-size: 14px;
        font-family: PingFangSC-Regular, 'PingFang SC';
        font-weight: 400;
        color: #33302d;
        line-height: 20px;

        span {
            color: #ff6b00;
        }
    }
}

.group-chat-list {
    display: flex;
    align-items: center;

    // flex-wrap: wrap;

    .list-item {
        min-width: 0;
        width: 202px;
        margin: 16px 8px 0 0;
        padding: 8px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        background: #f7f7f7;
        border-radius: 4px;

        .item-img {
            width: 36px;
            height: 36px;
        }

        .item-name {
            flex: 1;
            margin: 0 8px;
            font-size: 14px;
            color: #33302d;
            line-height: 20px;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
        }

        .el-icon {
            font-size: 16px;
            color: #ccc;

            &:hover {
                cursor: pointer;
                color: var(--el-text-color-placeholder);
            }
        }
    }

    .list-btn {
        margin-top: 16px;
        width: 36px;
        height: 52px;
        line-height: 52px;
        text-align: center;
        background: #f7f7f7;
        border-radius: 4px;
        cursor: pointer;
    }

    .list-btn-disabled {
        cursor: not-allowed;
    }
}

.group-chat-text-wrap {
}

.group-chat-text {
    padding: 16px;
    background: #fffaf9;
    border-radius: 4px;
    font-size: 14px;
    font-family: PingFangSC-Regular, 'PingFang SC';
    font-weight: 400;
    color: #696969;
    line-height: 20px;
    width: max-content;
}

.auto_send_switch-box {
    margin: 16px 0;
    padding: 16px;
    background: #f7f7f7;
    border-radius: 4px;
}

// 覆盖按钮样式
:deep(.el-button.el-button--primary.is-plain:not(.is-disabled)) {
    --el-button-bg-color: #fff;
    --el-button-border-color: var(--el-color-primary);

    &:hover {
        color: #ff6b00;
        border-color: #ff6b00;
        background-color: #fdefe5;
    }

    &:focus {
        color: #ff6b00;
        background-color: var(--el-button-bg-color);
        border: 1px solid #ffb580;
        outline: none;
    }
}
</style>
